<?php


namespace app\admin\controller;


use app\common\model\User;
use think\Controller;
use think\Request;
use app\common\model\User as UserModel;
use think\Session;

class LoginController extends Controller
{
    public function index()
    {
        return $this->fetch();
    }

    public function login()
    {

        $data = Request::instance()->post();
    //    判断用户是否存在/已注册
        $user = UserModel::get(['name'=>$data['name']]);
        if (is_null($user)){
            return $this->error('用户不存在,请先注册',null, '',1);
        }
    //    验证用户密码是否正确，当前为明文，后续要改
        if (!($user->password===$data['password'])){
            return $this->error('密码错误');
        }

        session(null);
        //写入session中
        session('user_id', $user->getData('id'));
        session('username', $user->getData('name'));
        session('is_super', $user->getData('is_super'));
        $this->setPermission($user->getData('id'));
    //    跳转到首页
        return $this->success('登录成功',$url=url('index/index'),'',1);
    }


    public function logout()
    {
        echo "logout";
    //    销毁session数据即可
    //     session('user_id', null);
    //     session('username', null);
        session(null);
        return $this->redirect(url('index'));
    }


    public function register()
    {

        if ($this->request->isGet()) {
            $html = $this->fetch('register');
            return $html;
        }


        // form表单提交逻辑
        $postData = Request::instance()->post();

        $user = UserModel::get(['name' => $postData['name']]);
        if (!is_null($user)) {
            return $this->error('用户名已存在', '', '', '2');
            // return json(['code'=>4000, 'message'=> '用户名已存在']);
        }
        // 用户未在库中，进行创建
        $user = new UserModel();
        $data = [
            'name'=> $postData['name'],
            'password' => $postData['password'],
            'phone' => $postData['mobile'],
            'group' => $postData['group'],
            'email' => $postData['email'],
        ];

         if ($user->allowField(true)->validate(true)->save($data)) {
             return $this->success('注册成功', 'index', '', 1);
         }
        return $this->success('添加成功吗', '', '', '1');
    }

    public function setPermission($uid)
    {
        $user = UserModel::get($uid);
        $permissions = array();
        //获取用户所有角色的权限，写session
        foreach ($user->auths as $auth) {
            $permissions = json_decode($auth['permission'], true);
        }

//        dump($permissions);
        session('permissions', $permissions);

    }

}